<!--
 * @author guojiteng
 新建/编辑考试
 -->
<template>
  <div class="a-rush-manage">
    <div class="a-rush-manage-title">新建/编辑考试</div>
    <section v-loading="loading" class="a-rush-manage-main">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        class="form"
      >
        <el-form-item label="考试名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入考试名称" maxlength="50" />
        </el-form-item>
        <el-form-item
          v-if="$route.query.type == 'u'"
          label="考试分类"
          prop="classifyId"
        >
          <el-cascader
            v-if="showClassify"
            ref="classify"
            v-model="form.classifyId"
            :options="classifyOptions"
            style="width: 100%"
            clearable
            :props="classifyProps"
          />
        </el-form-item>
        <el-form-item v-else label="考试分类" prop="classifyId">
          <el-cascader
            v-if="showClassify"
            ref="classify"
            v-model="form.classifyId"
            :options="classifyOptions"
            style="width: 100%"
            clearable
            :props="classifyProps"
          />
        </el-form-item>
        <!-- <el-form-item label="考试图片" prop="imgId">
          <image-upload
            :key="upload.imagecropperKey"
            v-model="form.imgId"
            :preview-id="upload.viewId"
            :forever="true"
            :width="330"
            :view="upload.view"
            :height="140"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            :is-oss="upload.isOss"
            @crop-success="picSuccess"
            @changeOssPath="
              (path) => {
                upload.viewId = path;
              }
            "
          />
          <p style="margin-bottom: 20px" />
        </el-form-item> -->
        <el-form-item label="题库:" prop="extend1">
          <el-cascader
            ref="classifys"
            v-model="form.extend1"
            :value="questionBankName"
            :options="classifyOptionss"
            style="width: 100%"
            clearable
            :props="classifyPropss"
          />
        </el-form-item>
        <section class="ct">
          <el-form-item label="单选题数量" prop="primaryQuesNum">
            <!-- <el-input
              v-model.number="form.primaryQuesNum"
              placeholder="请输入单选题数量"
            /> -->
            <el-input-number v-model="form.primaryQuesNum" :precision="0" :min="0" :max="999" :step="1" />
          </el-form-item>
          <el-form-item label="单选题分值" prop="primaryQuesFraction">
            <el-input-number v-model="form.primaryQuesFraction" :precision="2" :min="0" :max="999" />
          </el-form-item>
        </section>
        <section class="ct">
          <el-form-item label="多选题数量" prop="intermediateQuesNum">
            <!-- <el-input
              v-model.number="form.intermediateQuesNum"
              placeholder="请输入多选题数量"
            /> -->
            <el-input-number v-model="form.intermediateQuesNum" :precision="0" :min="0" :max="999" :step="1" />
          </el-form-item>
          <el-form-item label="多选题分值" prop="intermediateQuesFraction">
            <el-input-number v-model="form.intermediateQuesFraction" :precision="2" :min="0" :max="999" />
          </el-form-item>
        </section>
        <section class="ct">
          <el-form-item label="判断题数量" prop="advancedQuesNum">
            <!-- <el-input
              v-model.number="form.advancedQuesNum"
              placeholder="请输入判断题数量"
            /> -->
            <el-input-number v-model="form.advancedQuesNum" :precision="0" :min="0" :max="999" :step="1" />
          </el-form-item>
          <el-form-item label="判断题分值" prop="advancedQuesFraction">
            <el-input-number v-model="form.advancedQuesFraction" :precision="2" :min="0" :max="999" />
          </el-form-item>
        </section>
        <section class="ct">
          <el-form-item label="填空题数量" prop="technicianQuesNum">
            <!-- <el-input
              v-model.number="form.technicianQuesNum"
              placeholder="请输入填空题数量"
            /> -->
            <el-input-number v-model="form.technicianQuesNum" :precision="0" :min="0" :max="999" :step="1" />
          </el-form-item>
          <el-form-item label="填空题分值" prop="technicianQuesFraction">
            <el-input-number v-model="form.technicianQuesFraction" :precision="2" :min="0" :max="999" />
          </el-form-item>
        </section>
        <el-form-item label="考试开始日期" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            :picker-options="pickerOptions"
            style="width: 100%"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="考试结束日期" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            :picker-options="pickerOptions"
            style="width: 100%"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="考试总时长（秒）" prop="limitTime">
          <!-- <el-input
            v-model.number="form.limitTime"
            placeholder="请输入考试总时长（单位秒）"
          /> -->
          <el-input-number v-model="form.limitTime" :min="0" :max="99999999" :step="1" />
        </el-form-item>
        <el-form-item label="考试说明">
          <tinymce v-if="showtinymce" v-model="form.remark" :height="300" />
        </el-form-item>
        <el-form-item label="职工端是否展示" prop="isAppVisit">
          <el-radio-group v-model="form.isAppVisit" >
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <!-- <el-input
            v-model.number="form.sort"
            placeholder="请输入排序号（值越大，越靠前）"
          /> -->
          <el-input-number v-model="form.sort" :precision="0" :min="0" :max="999" :step="1" />
        </el-form-item>
      </el-form>
    </section>

    <section class="a-rush-manage-footer">
      <el-button style="padding: 10px 30px" @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
    <!--  选择题库  -->
    <el-dialog
      v-el-drag-dialog
      title="选择题库"
      :visible.sync="dialogPowerVisible"
      center
      width="450px"
      :close-on-click-modal="false"
    >
      <choose-qs
        v-if="dialogPowerVisible"
        ref="PowerTreeFun"
        :checked-data="form.quesBankClassifyIds"
        @subQs="getQsFun"
        @dialogPower="dialogPower"
      />
      <div slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px"
          @click="dialogPowerVisible = false"
        >取消</el-button>
        <el-button
          style="padding: 8px 30px"
          type="primary"
          @click="powerTreeFun"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { specialText, int, doublescore, intwith } from '@/utils/validate'
import { mapGetters } from 'vuex'
import ImageUpload from '@/components/ImageUpload'
import ChooseQs from '@/views/skill/answerRush/components/chooseQs'
import elDragDialog from '@/directive/el-drag-dialog'
import {
  getClassifyTree,
  insert,
  update,
  get,
  getClassifyTrees
} from './../api/manage'
import { queryPage } from '@/views/skill/answerRush/api/template'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'OnlineExamManage',
  components: { ImageUpload, ChooseQs, Tinymce },
  directives: { elDragDialog },
  data() {
    return {
      dialogPowerVisible: false,
      qsName: [],
      qsId: [],
      options: [], // 考试策略模板
      loading: false,
      showtinymce: false,
      questionBankName: '',
      form: {
        id: '',
        name: '',
        // imgId: '',
        classifyId: '',
        sort: '',
        limitTime: '',
        extend1: '',
        endTime: '',
        startTime: '',
        remark: '',
        primaryQuesNum: 0,
        primaryQuesFraction: '',
        intermediateQuesNum: 0,
        intermediateQuesFraction: '',
        advancedQuesNum: 0,
        advancedQuesFraction: '',
        technicianQuesNum: 0,
        technicianQuesFraction: '',
        isAppVisit:'1'
      },
      rules: {
        name: [
          { required: true, message: '请输入考试名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          }
        ],
        classifyId: [
          { required: true, message: '请选择考试分类', trigger: 'change' }
        ],

        extend1: [
          { required: true, message: '请选择题库', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        // remark: [
        //   { required: false, message: '请输入考试说明', trigger: 'blur' }
        // ],
        primaryQuesNum: [
          { required: true, message: '请输入单选题数量', trigger: 'blur' }
        ],
        primaryQuesFraction: [
          { required: true, message: '请输入单选题分值', trigger: 'blur' }
        ],
        intermediateQuesNum: [
          { required: true, message: '请输入多选题数量', trigger: 'blur' }
        ],
        intermediateQuesFraction: [
          { required: true, message: '请输入多选题分值', trigger: 'blur' }
        ],
        advancedQuesNum: [
          { required: true, message: '请输入判断题数量', trigger: 'blur' }
        ],
        advancedQuesFraction: [
          { required: true, message: '请输入判断题分值', trigger: 'blur' }
        ],
        technicianQuesNum: [
          { required: true, message: '请输入填空题数量', trigger: 'blur' }
        ],
        technicianQuesFraction: [
          { required: true, message: '请输入填空题分值', trigger: 'blur' }
        ],
        sort: [{ required: true, message: '请输入序号', trigger: 'blur' }],
        limitTime: [{ required: true, message: '请输入考试总时长', trigger: 'blur' }],
        isAppVisit: [{ required: true, message: '请选择是否在职工端进行展示', trigger: 'blur' }]
      },
      upload: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false
      },
      classifyProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true,
        emitPath: false
      },
      classifyPropss: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true,
        emitPath: false
      },
      classifyOptions: [],
      classifyOptionss: [],
      showClassify: false,
      state: 'create',
      t: '0',
      type: 1,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      }
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  watch: {
    'form.classifyId': {
      handler(newName, oldName) {
        if (this.$refs.classify) {
          this.$refs.classify.dropDownVisible = false
        }
      },
      immediate: true,
      deep: true
    },
    'form.extend1': {
      handler(newName, oldName) {
        if (this.$refs.classify) {
          this.$refs.classifys.dropDownVisible = false
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    this.getClassify()
    if (this.$route.query.type === 'u') {
      if (this.$route.query.i) {
        this.getData(this.$route.query.i)
      } else {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    } else {
      this.showClassify = true
      this.showtinymce = true
    }
  },

  methods: {
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id })
          .then((res) => {
            loading.close()
            const data = res.data.data
            this.form = data

            this.upload.viewId = data.imgIdUrl
            this.showtinymce = true
            console.log(data)
            this.$nextTick(() => {
              this.showClassify = true
            })
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    /**
     * 上传成功后重新校验
     * */
    picSuccess() {
      setTimeout(() => {
        this.$refs['form'].validateField('imgId', (val) => {
          if (!val) {
            return true
          } else {
            return false
          }
        })
      }, 1500)
    },
    /**
     * 去掉某个题库
     * */
    handleClose(i) {
      this.form.quesBankClassifyIds.splice(i, 1)
      this.qsName.splice(i, 1)
    },
    /**
     * 获取考试策略模板
     * */
    getList() {
      var query = {
        page: 1,
        pageSize: 9999
      }
      return new Promise((resolve, reject) => {
        queryPage(query)
          .then((response) => {
            this.options = response.data.data.rows || []
          })
          .catch((error) => {
            reject(error)
            this.listLoading = false
          })
      })
    },
    /**
     * 题库
     */
    getQsFun(obj) {
      this.qsName = obj.menuName
      this.form.quesBankClassifyIds = obj.menuIds
      this.$refs['form'].validateField('quesBankClassifyIds', (val) => {
        if (!val) {
          return true
        } else {
          return false
        }
      })
    },
    /**
     * 关闭权限弹框
     */
    dialogPower(val) {
      this.dialogPowerVisible = val
    },
    /**
     * 确认题库
     */
    powerTreeFun() {
      this.$refs.PowerTreeFun.saveData()
      this.dialogPowerVisible = false
    },
    /**
     * 获取分类
     */
    getClassify() {
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'JNZQFL09' })
          .then(({ data }) => {
            this.classifyOptions = data.data || []
            this.getClassifys()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /**
     * 获取题库分类
     */
    getClassifys() {
      return new Promise((resolve, reject) => {
        getClassifyTrees({ classifyType: 'JNZQFL03' })
          .then(({ data }) => {
            this.classifyOptionss = data.data || []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    /**
     * 取消考试维护
     */
    onCancel() {
      this.$router.push({
        path: this.$filterPath('index'),
        query: { t: this.t }
      })
    },

    /**
     * 发布考试
     */
    onSubmint() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const obj = Object.assign({}, this.form)
            return new Promise((resolve, reject) => {
              insert(obj)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ path: this.$filterPath('index') })
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const obj = Object.assign({}, this.form)
            if (Array.isArray(obj.extend1)) {
              obj.extend1 =
                  obj.extend1.length > 0
                    ? obj.extend1[obj.extend1.length - 1]
                    : ''
            }
            delete obj.imgIdUrl
            return new Promise((resolve, reject) => {
              update(obj)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '编辑成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ path: this.$filterPath('index') })
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            return false
          }
        })
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.a-rush-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  .a-rush-manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: "";
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .a-rush-manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
    .ct {
      display: flex;
      width: 100%;
    }
    .form {
      width: 1000px !important;
      margin: 0 auto;
      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }
    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;
      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }
    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
    }
  }
  .a-rush-manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
<style lang="scss">
.a-rush-manage {
  .classify-tree-con {
    position: relative;
    height: 400px;
    overflow: hidden;
    .classify-tree-con-scrollbar {
      overflow: hidden;
      .el-scrollbar__wrap {
        max-height: 381px;
      }
    }
    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      width: 100%;
      .tree-node-txt {
        flex: 1;
      }
    }
  }
}
</style>

